package cn.bitkit.tools.crypto;

import cn.bitkit.base.util.StringUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * 
 * @author changbo
 *
 */
@Slf4j
public class DES {
	
	private final static String KEY_ALGORITHM = "DES";
    private final static String CIPHER_ALGORITHM = "DES/ECB/NoPadding";
    private final static String KEY_ALGORITHM_3 = "DESede";
    private final static String CIPHER_ALGORITHM_3 = "DESede/ECB/NoPadding";

    public static String encrypt(String src, String key) {
        return cipher(src, key, Cipher.ENCRYPT_MODE);
    }

    public static String decrypt(String src, String key) {
        return cipher(src, key, Cipher.DECRYPT_MODE);
    }

    public static String cipher(String src, String key, int mode) {
        byte[] res = cipherByte(StringUtil.hexStrToBytes(src), StringUtil.hexStrToBytes(key),
                KEY_ALGORITHM, CIPHER_ALGORITHM, mode);
        return StringUtil.bytesToHexStr(res);
    }

    @SneakyThrows
    public static byte[] cipherByte(byte[] src, byte[] key, String keyAlgorithm, String cipherAlgorithm, int mode) {
        DESKeySpec keySpec = new DESKeySpec(key);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(keyAlgorithm);
        SecretKey secretKey = keyFactory.generateSecret(keySpec);
        Cipher cipher = Cipher.getInstance(cipherAlgorithm);
        cipher.init(mode, secretKey);
        return cipher.doFinal(src);
    }

    public static String encrypt3(String src, String key) {
        return cipher3(src, key, Cipher.ENCRYPT_MODE);
    }

    public static String decrypt3(String src, String key) {
        return cipher3(src, key, Cipher.DECRYPT_MODE);
    }

    public static String cipher3(String src, String key, int mode) {
        byte[] res = cipherByte3(StringUtil.hexStrToBytes(src), StringUtil.hexStrToBytes(key),
                KEY_ALGORITHM_3, CIPHER_ALGORITHM_3, mode);
        return StringUtil.bytesToHexStr(res);
    }

    @SneakyThrows
    public static byte[] cipherByte3(byte[] src, byte[] key, String keyAlgorithm, String cipherAlgorithm, int mode) {
        byte[] keyBytes = new byte[24];
        System.arraycopy(key, 0, keyBytes, 0, 16);
        SecretKey secretKey = new SecretKeySpec(keyBytes, keyAlgorithm);
        Cipher cipher = Cipher.getInstance(cipherAlgorithm);
        cipher.init(mode, secretKey);
        return cipher.doFinal(src);
    }

}
